package com.ytc.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ytc.commons.constants.OrdersConstants;
import com.ytc.commons.enums.ErrorCode;
import com.ytc.commons.model.vo.ResponseResult;
import com.ytc.order.domain.Orders;
import com.ytc.order.domain.Payment;
import com.ytc.order.mappers.PaymentMapper;
import com.ytc.order.service.OrdersService;
import com.ytc.order.service.PaymentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ytc.order.utils.PayUtils;
import com.ytc.web.exception.BusinessException;
import com.ytc.web.interceptor.AuthInfoHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 订单支付信息 服务实现类
 * </p>
 *
 * @author jiuye145
 * @since 2023-04-09
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private PayUtils payUtils;

    @Override
    public ResponseResult<String> createPay(String orderNo) {
        //查询订单，判断订单状态
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getOrderNo,orderNo);
        Orders one = ordersService.getOne(wrapper);
        if(!one.getStatus().equals(OrdersConstants.ORDER_INIT_STATUS)) {
            throw new BusinessException(ErrorCode.PAYERROR);
        }
        //查询支付信息，看是否存在
        LambdaQueryWrapper<Payment> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Payment::getOrderNo,orderNo);
        Payment one1 = this.getOne(wrapper1);
        //3、构造支付数据，存入到数据库中
        if(one1 == null) {
            one1 = new Payment();
            one1.setUserId(AuthInfoHolder.getUserId());
            one1.setOrderNo(orderNo);
            one1.setCompanyId(one.getCompanyId());
            one1.setTotalAmount(one.getPrice());
            one1.setCreateDate(new Date());
            one1.setPayMethod(OrdersConstants.PAY_METHOD_WX);//支付方式
            one1.setStatus(OrdersConstants.NOT_PAID.toString());
            boolean save = this.save(one1);
            if (!save) {
                throw new BusinessException(ErrorCode.ERROR);
            }
        }
        //调用微信工具类生成二维码
        String url = payUtils.createOrder(one1.getOrderNo(),one1.getTotalAmount(),one.getCoursePubName());
        //返回
        return ResponseResult.okResult(url);

    }
}
